package com.enjoy.mall.sentinel.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.tuling.mall.common.R;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Collections;

@RestController
public class HelloController {


    private static final String RESOURCE_NAME = "whh";

    @RequestMapping("/hello")
    public R findUser() {
        Entry entry = null;

        try {
            entry = SphU.entry(RESOURCE_NAME);
            System.out.println("正常访问");

        } catch (Exception e){
            System.out.println("限流了");
            return R.error(500, "限流了!");
        } finally {
            if (entry != null) {
                entry.close();
                entry.exit();
            }
        }
        return R.success();
    }

    @PostConstruct
    private static void initFlowRules() {
        FlowRule flowRule = new FlowRule();

        flowRule.setResource(RESOURCE_NAME);

        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);

        flowRule.setCount(1);

        FlowRuleManager.loadRules(Collections.singletonList(flowRule));
    }
}
